package com.w3coffee.web.control;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

public class CheckinRequestController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public ModelAndView handleRequest(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		/* 创建session */
		HttpSession session = req.getSession();

		/* 把Http request中的backUrl参数保存到session中 */
		String backUrl = (String) req.getParameter("backUrl");
		session.setAttribute("backUrl", backUrl);

		CheckinToken token = (CheckinToken) session.getAttribute("TOKEN");
		if (token == null) {
			token = getCheckinTokenFromCookie(req);
			session.setAttribute("TOKEN", token);
		}

		CheckinAction ca = token.getCheckinAction();
		Map<String, Object> model = getDefaultModel(req);
		if (ca == CheckinAction.login_and_verify_location) {
			return adaptive(req, resp, "loginAndVerifyLocation", model);
		} else if (ca == CheckinAction.only_verify_location) {
			return adaptive(req, resp, "onlyVerifyLocation", model);
		} else {
			if (backUrl != null) {
				resp.sendRedirect(backUrl);
				return null;
			} else {
				return adaptive(req, resp, "welcome", model);
			}
		}
	}

	private CheckinToken getCheckinTokenFromCookie(HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		if (cookies == null) {
			return new CheckinToken();
		}

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("TOKEN")) {
				String val = cookie.getValue();
				try {
					int tid = Integer.parseInt(val);
					return new CheckinToken(tid);
				} catch (Exception e) {
					return new CheckinToken();
				}
			}
		}
		
		return new CheckinToken();
	}
}
